<script lang="ts" setup>
import Blockly from 'blockly'
import DarkTheme from '@blockly/theme-dark'
import * as Ch from 'blockly/msg/zh-hans'
import { nextTick, onMounted } from 'vue'
import { toolBox } from '@/stores/blockEditor.toolbox.ts'
import { pythonGenerator } from 'blockly/python'
import { debounce } from '@/utils/commonTool'
// import { useBlockEditor } from '@/hooks/blockEditor.ts'
defineOptions({
  name: 'blockEditor'
})

Blockly.setLocale(Ch)

let workspace: WorkSpaceSvg

// const { setCustomTheme } = useBlockEditor(Blockly)
//
// 初始化工作区
const initBlockWorkSpace = () => {
  //   setCustomTheme()
  workspace = Blockly.inject('blocklyDiv', {
    toolbox: toolBox,
    theme: DarkTheme
  })
}
onMounted(() => {
  initBlockWorkSpace()
})

const resizeWorkSpace = () => {
  //   console.log('resize...')
  // nextTick确保页面更新
  nextTick(() => {
    Blockly.svgResize(workspace)
  })
}

const emit = defineEmits(['update:code'])
const updateCode = () => {
  const code = pythonGenerator.workspaceToCode(workspace)
  // console.log(code)
  emit('update:code', code)
  // return code
}
const listenWorkSpaceChange = () => {
  const debounceUpdateFunction = debounce(updateCode, 200)
  workspace.addChangeListener(event => {
    debounceUpdateFunction()
  })
}
onMounted(() => {
  listenWorkSpaceChange()
})
defineExpose({ resizeWorkSpace })
</script>

<template>
  <div class="block-editor">
    <div id="blocklyDiv" style="height: 100%; width: 100%"></div>
  </div>
</template>

<style lang="scss" scoped>
.block-editor {
  width: 100%;
  height: 100%;
  background-color: pink;
}
</style>
